#!/usr/local/python/bin/python
# coding=utf-8
__author__ = 'zhuhui'


import ftplib
from tools import Config


class FtpUtil:
    _ftp = None

    def login(self):
        self._ftp = ftplib.FTP()
        self._ftp.connect(Config.FTP_HOSTNAME, Config.FTP_PORT)
        self._ftp.login(Config.FTP_USER, Config.FTP_PASSWD)

    def getFile(self, remotePath, localPathFile, fileName):
        try:
            self.login()
            self._ftp.cwd(remotePath)
            f = open(localPathFile, 'wb')
            self._ftp.retrbinary("RETR " + fileName, f.write())
            f.close()
        finally:
            self.close()

    def getFileEx(self, remotePath, localPath, fileName):
        try:
            self.getFile(remotePath, localPath, fileName)
            return True
        except Exception as e:
            print "Error:" + e.message
            return False

    def close(self):
        if (self._ftp):
            try:
                self._ftp.close()
            except Exception as e:
                pass


